package org.example.struct.array;

/**
 * @author liyishan
 * @date 2023/12/29 10:45
 * @apiNote
 */

public class Test00067AddBinary {

    public static void main(String[] args) {
        String a = "1010", b = "1011";
        System.out.println(addBinary1(a, b));
    }

    public String addBinary(String a, String b) {
        StringBuffer ans = new StringBuffer();
        int n = Math.max(a.length(), b.length()), carry = 0;
        for (int i = 0; i < n; ++i) {
            carry += i < a.length() ? (a.charAt(a.length() - 1 - i) - '0') : 0;
            carry += i < b.length() ? (b.charAt(b.length() - 1 - i) - '0') : 0;
            ans.append((char) (carry % 2 + '0'));
            carry /= 2;
        }

        if (carry > 0) {
            ans.append('1');
        }
        ans.reverse();
        return ans.toString();
    }

    public static String addBinary1(String a, String b) {
        int x = Integer.parseInt(a,2);
        int y = Integer.parseInt(b,2);
        while (y != 0) {
            int temp = x ^y;
            int carry = (x & y) << 1;
            x = temp;
            y = carry;
        }
        return Integer.toBinaryString(x);
    }

}
